from flask import abort
from flask import current_app
from flask import g
from flask import session

from info import constants, db
from info.models import User, News
from info.modules.news_detail import detail_blu
from flask import render_template

from info.utils.common import get_user_cookie


@detail_blu.route('/<int:news_id>')
@get_user_cookie
def news_detail(news_id):



    user = g.user

    #点击排行处理区域
    #1.获取数据库新闻点击数据排行
    new_click =None
    try:
        new_click = News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)


    #2.新闻详情信息的查询
    newsDetail =None
    try:
        newsDetail = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not newsDetail:
        abort(404)

    newsDetail.clicks += 1

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)

    data={
        'user_id':user.to_dict() if user else None,
        'new_click':new_click,
        'newsDetail':newsDetail
    }


    return render_template('news/detail.html',data=data)